// @ts-ignore
import DPlayer from 'dplayer';
const Hls = require('hls.js');
import 'xgplayer/dist/index.min.css';
import { getSign } from '@/components/ossUpload/service';
import { message, Modal, UploadFile } from 'antd';
import { useEffect, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { ProFormUploadButton } from '@ant-design/pro-form';
import { Rule } from 'antd/lib/form';
let player: any;
const VideoUpload: React.FC<{ name: string; label: string; rules?: Rule[] }> = ({
    name,
    label,
    rules,
}) => {
    const [OSSData, setOSSData] = useState<{
        accessId: string;
        callback: string;
        dir: string;
        expire: 1661844820;
        fileName: string;
        host: string;
        policy: string;
        signature: string;
        key: string;
        m3u8: string;
    }>();
    const [isVideoShow, setIsVideoShow] = useState(false);

    const getExtraData = (file: any) => ({
        policy: OSSData?.policy,
        ossaccessKeyId: OSSData?.accessId,
        key: OSSData?.key + file.name,
        dir: OSSData?.dir,
        host: OSSData?.host,

        signature: OSSData?.signature,
    });
    const init = async () => {
        try {
            const response = await getSign({
                accessId: 'c75dd105201d4d96a23164bf2f540061',
                accessSecret: '0134468d09afc43b3005d4d8f391d38c',
                type: 1,
                file_dir: 'm3u8'
            });
            response.key = response.dir + response.fileName;
            setOSSData(response);

            return response;
        } catch (error) {
            message.error(error);
            return false;
        }
    };

    const beforeUpload = async (file: any) => {
        let temp = await init();
        if (!temp) return false;
        const expire = Number(temp.expire) * 1000;
        if (expire < Date.now()) {
            temp = await init();
        }

        file.url = temp.host + '/m3u8/' + temp.fileName + file.name.replace(/\.(\w*)$/, '.m3u8')
        // file.url = temp.host + temp.dir + file.name.replace(/\.(\w*)$/, '.m3u8');
        console.log('file.url', file.url);
        return file;
    };

    useEffect(() => {
        return () => {
            if (player && player?.destroy) {
                player.destroy();
                player = null;
            }
        };
    }, []);

    const onPreview = (file: UploadFile<any>) => {
        setIsVideoShow(true);
        // 掉入宏任务 保证ui先加载出来
        setTimeout(() => {
            player = new DPlayer({
                container: document.getElementById('mse'), // 注意：这里一定要写div的dom
                lang: 'zh-cn',
                video: {
                    url: file.url, // 这里填写.m3u8视频连接
                    type: 'customHls',
                    customType: {
                        customHls: function (video: any) {
                            const hls = new Hls();
                            hls.loadSource(video.src);
                            hls.attachMedia(video);
                        },
                    },
                },
            });
        });
    };
    return (
        <>
            <ProFormUploadButton
                name={name}
                label={label}
                max={1}
                icon={
                    <div>
                        <PlusOutlined />
                    </div>
                }
                title="Upload"
                fieldProps={{
                    name: 'file',
                    accept: 'video/*',
                    listType: 'picture-card',
                    data: getExtraData,
                    beforeUpload,
                    onPreview,
                }}
                action={OSSData?.host}
                rules={rules}
            />
            <Modal
                open={isVideoShow}
                footer={null}
                width={800}
                onCancel={() => setIsVideoShow(false)}
                destroyOnClose
            >
                <div id="mse"></div>
            </Modal>
        </>
    );
};

export default VideoUpload;
